package com.jrx.anytxn.transaction.job.consumeRemind.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import com.jrx.anytxn.param.utils.BizTypeProducts;
import com.jrx.anytxn.ribbon.config.GrayVersionConfig;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.job.consumeRemind.step.ConsumeRemindProcessor;
import com.jrx.anytxn.transaction.job.consumeRemind.step.ConsumeRemindWriter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 消费提醒短信
 *
 * @author bowen.liu
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class ConsumeRemindConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(ConsumeRemindConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    public GrayVersionConfig grayVersionConfig;

    @Autowired
    public ConsumeRemindProcessor consumeRemindProcessor;

    @Autowired
    public ConsumeRemindWriter consumeRemindWriter;

    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;

    @Autowired
    DataSource dataSource;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Resource
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;

    @Bean
    public Job consumeRemindJob() {
        return jobBuilderFactory.get("consumeRemindJob")
                .start(consumeRemindStep())
                .build();
    }

    @Bean
    public Step consumeRemindStep() {
        return stepBuilderFactory.get("consumeRemindStep")
                .<AmLoanMainInfo, AmLoanMainInfo>chunk(anytxnBatchProperties.getDefaultConfig().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(consumeRemindReader())
                .processor(consumeRemindProcessor)
                .writer(consumeRemindWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getDefaultConfig().getThrottleLimit())//多线程
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<AmLoanMainInfo> consumeRemindReader() {
        //同步reader   线程安全
        MyBatisCursorItemReader<AmLoanMainInfo> accrualCursorReader = new MyBatisCursorItemReader<>();
        accrualCursorReader.setSaveState(false);
        accrualCursorReader.setSqlSessionFactory(sqlSessionFactory);
        accrualCursorReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper.getLoanCustomerInfoByTime");

        PrOrganizationTable org = extPrOrganizationTableMapper.selectByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);

        Map<String, Object> map = new HashMap<>();
        map.put("productId", BizTypeProducts.PRODUCT_XYJY);
        map.put("startTime", DateUtils.format(org.getToday(), DateUtils.DATE_PATTERN));
        map.put("endTime", DateUtils.format(org.getNextProcessingDate(), DateUtils.DATE_PATTERN));
        accrualCursorReader.setParameterValues(map);
        //同步reader   线程安全
        SynchronizedItemStreamReader<AmLoanMainInfo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(accrualCursorReader);
        return synchronizedItemStreamReader;
    }
}
